#!/bin/bash
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

[[ "$1" != "@NCSI_IF@" ]] && exit 0

HAS_DHCRELAY='@GBMC_DHCP_RELAY@'

if [ "$HAS_DHCRELAY" = 1 ]; then
  # Remove the source relay port from the relay, bringing it back to run on
  # the default port 547. Our relays don't support the source port option needed
  # to run on 3967 for our legacy NICs.
  echo 'RP_FLAG=' >/run/gbmc-ncsi-dhcrelay.env
  systemctl reset-failed gbmc-ncsi-dhcrelay
  systemctl restart --no-block gbmc-ncsi-dhcrelay
fi

echo '@NCSI_IF@' >>/run/gbmc-br-dhcp-intfs
if systemctl is-active --quiet gbmc-br-dhcp@gbmcbr; then
  systemctl reset-failed gbmc-br-dhcp@@NCSI_IF@
  systemctl restart --no-block gbmc-br-dhcp@@NCSI_IF@
fi

read -r -d '' contents <<EOF
table inet filter {
  chain ncsi_legacy_input {
    udp dport {546,547} accept
  }
  chain ncsi_input {
    jump ncsi_gbmc_br_pub_input
  }
}
EOF
rfile=/run/nftables/40-gbmc-ncsi-smartnic.rules
mkdir -p "$(dirname "$rfile")"
printf '%s' "$contents" >"$rfile"
systemctl reset-failed nftables
systemctl --no-block reload-or-restart nftables
